package com.ymttest.business.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.client.ClientProtocolException;

import com.ymatou.iapi.auth.parameter.*;
import com.ymatou.iapi.auth.service.*;
import com.ymatou.iapi.login.parameter.*;
import com.ymatou.iapi.login.service.*;
import com.ymatou.iapi.usersafe.parameter.*;
import com.ymatou.iapi.usersafe.service.*;
import com.ymatou.iapi.userservice.parameter.enums.AppSourceEnum;
import com.ymatou.iapi.userservice.parameter.enums.TerminalSourceEnum;
import com.ymt.core.tool.Logger;
import com.ymttest.database.sqlwapper.JUserWapper;
import com.ymttest.utils.TestDataManager;

/************************************************************************************
 * @File name :AuthCallService.java
 * @Author : zhouyi
 * @Date : 2015年10月17日
 * @Copyright : 洋码头
 ************************************************************************************/
public class AuthCallServiceV2 {
	static Map<String, Map> loginCache = new HashMap<String, Map>();

	/**
	 * 登入 获取AccessToken
	 */
	@SuppressWarnings("rawtypes")
	public static Map<String, Object> authLogin(String UserName, String pas) {
		HashMap m = new HashMap();
		try {
			// 添加loginCache缓存，由于目前auth添加了风控频繁登入会失败，所以登入后保存在静态Map中，使用前signAuth保证可用
			if (loginCache.containsKey(UserName)) {
				Map mtemp = loginCache.get(UserName);
				String tuid = String.valueOf(signAuth(mtemp.get("accessToken").toString()).get("userId"));
				if (tuid.equals(mtemp.get("userId").toString())) {
					return mtemp;
				}
			}
			LoginAuthBean lab = new LoginAuthBean();
			LoginAuthCall lac = new LoginAuthCall();
			lab.setLoginId(UserName);
			lab.setPas(pas);
			lab.setSourceType("MainSite");
			// lab.setClientIp(TestDataManager.getRandomIp());
			lab.setClientIp("127.16.14.35");
			lac.setData(false, lab);
			Logger.comment("用户:" + UserName + "登录");
			lac.callService();
			m.put("userId", lac.getUserData().getUserId());
			m.put("userName", lac.getUserData().getLoginId());
			m.put("accessToken", lac.getUserData().getSign());
			m.put("loginMobile", lac.getUserData().getLoginMobile());
			loginCache.put(UserName, m);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return m;
	}

	public static Map<String, Object> authLogin(String UserName, String pas, String sourceType, String ip) {
		HashMap m = new HashMap();
		try {
			// 添加loginCache缓存，由于目前auth添加了风控频繁登入会失败，所以登入后保存在静态Map中，使用前signAuth保证可用
			if (loginCache.containsKey(UserName)) {
				Map mtemp = loginCache.get(UserName);
				String tuid = String.valueOf(signAuth(mtemp.get("accessToken").toString()).get("userId"));
				if (tuid.equals(mtemp.get("userId").toString())) {
					return mtemp;
				}
			}
			LoginAuthBean lab = new LoginAuthBean();
			LoginAuthCall lac = new LoginAuthCall();
			lab.setLoginId(UserName);
			lab.setPas(pas);
			lab.setSourceType(sourceType);
			lab.setClientIp(ip);
			lac.setData(false, lab);
			Logger.comment("用户:" + UserName + "登录");
			lac.callService();
			m.put("userId", lac.getUserData().getUserId());
			m.put("userName", lac.getUserData().getLoginId());
			m.put("accessToken", lac.getUserData().getSign());
			m.put("loginMobile", lac.getUserData().getLoginMobile());
			if (lac.getString("Success").equals("true")) {
				loginCache.put(UserName, m);
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return m;
	}

	public static Map<String, Object> authLogin(String UserName, String pas, String sourceType, String ip, String tokenSource) {
		HashMap m = new HashMap();
		try {
			// 添加loginCache缓存，由于目前auth添加了风控频繁登入会失败，所以登入后保存在静态Map中，使用前signAuth保证可用
			if (loginCache.containsKey(UserName)) {
				Map mtemp = loginCache.get(UserName);
				String tuid = String.valueOf(signAuth(mtemp.get("accessToken").toString()).get("userId"));
				if (tuid.equals(mtemp.get("userId").toString())) {
					return mtemp;
				}
			}
			LoginAuthBean lab = new LoginAuthBean();
			LoginAuthCall lac = new LoginAuthCall();
			lab.setLoginId(UserName);
			lab.setPas(pas);
			lab.setSourceType(sourceType);
			lab.setClientIp(ip);
			lab.setTokenSource(tokenSource);
			lac.setData(false, lab);
			Logger.comment("用户:" + UserName + "登录");
			lac.callService();
			m.put("userId", lac.getUserData().getUserId());
			m.put("userName", lac.getUserData().getLoginId());
			m.put("accessToken", lac.getUserData().getSign());
			m.put("loginMobile", lac.getUserData().getLoginMobile());
			if (lac.getString("Success").equals("true")) {
				loginCache.put(UserName, m);
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return m;
	}

	public static LoginAuthCall login(String UserName, String pas, String sourceType, String ip) {

		LoginAuthBean lab = new LoginAuthBean();
		LoginAuthCall lac = new LoginAuthCall();

		try {

			lab.setLoginId(UserName);
			lab.setPas(pas);
			lab.setSourceType(sourceType);
			lab.setClientIp(ip);
			lac.setData(false, lab);
			Logger.comment("用户:" + UserName + "登录");
			lac.callService();

		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return lac;
	}

	/**
	 * Token认证
	 */
	@SuppressWarnings("rawtypes")
	public static Map<String, Object> signAuth(String AccessToken, String ip) {
		HashMap m = new HashMap();
		try {
			SignAuthBean sab = new SignAuthBean();
			SignAuthCall sac = new SignAuthCall();
			sab.setToken(AccessToken);
			sab.setClientIp(ip);
			sac.setData(false, sab);
			Logger.comment("用户token登录认证");
			sac.callService();
			Logger.debug("Token认证 call:" + sac.getEntityString());
			Logger.debug("Token认证 response:" + sac.getReturnData());
			m.put("success", sac.getSuccess());
			if (sac.getSuccess()) {
				m.put("userId", sac.getUserId());
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return m;
	}

	/**
	 * Token认证
	 */
	@SuppressWarnings("rawtypes")
	public static Map<String, Object> signAuth(SignAuthBean sab) {
		HashMap m = new HashMap();
		try {
			SignAuthCall sac = new SignAuthCall();
			sac.setData(false, sab);
			Logger.comment("用户token登录认证");
			sac.callService();
			m.put("success", sac.getSuccess());
			if (sac.getSuccess()) {
				m.put("userId", sac.getUserId());
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return m;
	}

	/**
	 * 创建token 如果有则返回现有token
	 * 
	 * @param uid
	 * @param tokenSource
	 * @return
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static String createToken(Integer uid, String tokenSource) throws ClientProtocolException, IOException {
		UserTokenDtoBean usertokendtoBean = new UserTokenDtoBean();
		UserTokenDtoCall usertokendtoCall = new UserTokenDtoCall();
		usertokendtoBean.setUserId(uid);
		usertokendtoBean.setTokenSource(tokenSource);
		usertokendtoCall.setData(usertokendtoBean);
		usertokendtoCall.callService();
		try {
			//mongo主从同步慢
			Thread.sleep(500);
		} catch (InterruptedException e) {
		}
		return usertokendtoCall.getResult();
	}
	public static String createToken(Integer uid, String tokenSource,String deviceid) throws ClientProtocolException, IOException {
		UserTokenDtoBean usertokendtoBean = new UserTokenDtoBean();
		UserTokenDtoCall usertokendtoCall = new UserTokenDtoCall();
		usertokendtoBean.setUserId(uid);
		usertokendtoBean.setTokenSource(tokenSource);
		usertokendtoBean.setDeviceId(deviceid);
		usertokendtoCall.setData(usertokendtoBean);
		usertokendtoCall.callService();
		return usertokendtoCall.getResult();
	}
	/**
	 * @param AccessToken
	 * @return map(success,userId)
	 */
	@SuppressWarnings("rawtypes")
	public static Map<String, Object> signAuth(String AccessToken) {
		HashMap m = new HashMap();
		try {
			SignAuthBean sab = new SignAuthBean();
			SignAuthCall sac = new SignAuthCall();
			sab.setToken(AccessToken);
			sac.setData(false, sab);
			Logger.comment("用户token登录认证");
			sac.callService();
			Logger.debug("Token认证 call:" + sac.getEntityString());
			Logger.debug("Token认证 response:" + sac.getReturnData());
			m.put("success", sac.getSuccess());
			if (sac.getSuccess()) {
				m.put("userId", sac.getUserId());
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return m;
	}

	/**
	 * @param AccessToken
	 * @return map(success,userId)
	 */

	/**
	 * Token认证
	 */
	@SuppressWarnings("rawtypes")
	public static Map<String, String> removeAuth(String AccessToken) {
		HashMap m = new HashMap();
		try {
			UserRemoveTokenRequestDtoBean lab = new UserRemoveTokenRequestDtoBean();
			UserRemoveTokenRequestDtoCall lac = new UserRemoveTokenRequestDtoCall();
			lab.setToken(AccessToken);
			lac.setData(false, lab);
			lac.callService();
			Logger.debug("移除Token认证 call:" + lac.getEntityString());
			Logger.debug("移除Token认证 response:" + lac.getReturnData());

		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return m;
	}

	/**
	 * *更新用户的IP区域认证状态为已认证
	 */
	@SuppressWarnings("rawtypes")
	public static IpAreaAuthManageRequestDtoCall ipAreaAuthManage(String country, String province, String city, int userid) {
		IpAreaAuthManageRequestDtoBean ipareaauthmanagerequestdtoBean = new IpAreaAuthManageRequestDtoBean();
		IpAreaAuthManageRequestDtoCall ipareaauthmanagerequestdtoCall = new IpAreaAuthManageRequestDtoCall();
		try {
			ipareaauthmanagerequestdtoBean.setCountry(country);
			ipareaauthmanagerequestdtoBean.setProvince(province);
			ipareaauthmanagerequestdtoBean.setCity(city);
			ipareaauthmanagerequestdtoBean.setUserId(userid);
			ipareaauthmanagerequestdtoCall.setData(ipareaauthmanagerequestdtoBean);
			ipareaauthmanagerequestdtoCall.callService();

		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return ipareaauthmanagerequestdtoCall;
	}

	/**
	 * 收集风控数据
	 * 
	 * @param uid
	 * @param authSuccesss
	 * @return
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static VerifyDataGatherCall VerifyDataGather(Integer uid, boolean authSuccesss, String ip) throws ClientProtocolException, IOException {
		VerifyDataGatherBean VerifyDataGatherBean = new VerifyDataGatherBean();
		VerifyDataGatherCall VerifyDataGatherCall = new VerifyDataGatherCall();
		String loginid = new JUserWapper().selectUserinfoByUid(uid).get(0).getLoginId();
		VerifyDataGatherBean.setLoginId(loginid);
		VerifyDataGatherBean.setUserId(uid);
		VerifyDataGatherBean.setLoginIp(ip);
		VerifyDataGatherBean.setAuthSuccess(authSuccesss);
		VerifyDataGatherBean.setAppSource(AppSourceEnum.App.name());
		VerifyDataGatherBean.setDeviceId(TestDataManager.getRandomUUID().toString());
		VerifyDataGatherBean.setGatherTriggerType(GatherTriggerTypeEnum.BeforeLogin);
		VerifyDataGatherBean.setLoginType(LoginTypeEnum.SafeLogin);
		VerifyDataGatherBean.setTerminalSource(TerminalSourceEnum.IOS.name());
		VerifyDataGatherCall.setData(VerifyDataGatherBean);
		VerifyDataGatherCall.callService();
		return VerifyDataGatherCall;
	}

	/**
	 * 认证IP
	 * 
	 * @param ip
	 *            登陆IP
	 * @param loginId
	 *            登录Id
	 * @param pwd
	 *            登陆密码
	 * @param sourceType
	 *            使用的终端（mainsite, main...）
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static void authIPArea(String ip, String loginId, String pwd, String sourceType) throws ClientProtocolException, IOException {
		IpAreaAuthStatusRequestDtoBean ipareaauthstatusrequestdtoBean = new IpAreaAuthStatusRequestDtoBean();
		IpAreaAuthStatusRequestDtoCall ipareaauthstatusrequestdtoCall = new IpAreaAuthStatusRequestDtoCall();
		ipareaauthstatusrequestdtoBean.setIp(ip);
		ipareaauthstatusrequestdtoBean.setLoginId(loginId);
		ipareaauthstatusrequestdtoBean.setPassword(pwd);
		ipareaauthstatusrequestdtoBean.setSuccess(true);
		ipareaauthstatusrequestdtoBean.setSource(sourceType);
		ipareaauthstatusrequestdtoCall.setData(ipareaauthstatusrequestdtoBean);
		ipareaauthstatusrequestdtoCall.callService();
		Logger.verifyEquals("true", ipareaauthstatusrequestdtoCall.getString("Success"), "验证认证成功");
	}

	/**
	 * 设备认证
	 * 
	 * @param clientId
	 *            设备clientId
	 * @param deviceId
	 *            设备Id
	 * @param loginId
	 *            登录Id
	 * @param pwd
	 *            登陆密码
	 * @param sourceType
	 *            登陆终端
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static void authApp(String clientId, String deviceId, String loginId, String pwd, String sourceType) throws ClientProtocolException, IOException {
		DeviceAuthStatusRequestDtoBean deviceauthstatusrequestdtoBean = new DeviceAuthStatusRequestDtoBean();
		DeviceAuthStatusRequestDtoCall deviceauthstatusrequestdtoCall = new DeviceAuthStatusRequestDtoCall();
		deviceauthstatusrequestdtoBean.setClientId(clientId);
		deviceauthstatusrequestdtoBean.setDeviceId(deviceId);
		deviceauthstatusrequestdtoBean.setIp(TestDataManager.getRandomIp());
		deviceauthstatusrequestdtoBean.setLoginId(loginId);
		deviceauthstatusrequestdtoBean.setPassword(pwd);
		deviceauthstatusrequestdtoBean.setSource(sourceType);
		deviceauthstatusrequestdtoBean.setSuccess(true);
		deviceauthstatusrequestdtoCall.setData(deviceauthstatusrequestdtoBean);
		deviceauthstatusrequestdtoCall.callService();
		Logger.verifyEquals("true", deviceauthstatusrequestdtoCall.getString("Success"), "验证认证成功");
	}

	/**
	 * @param loginId
	 * @param ip
	 * @param type
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static IpAreaAuthStatusRequestDtoCall ipAreaAuthStatus(String loginId, String ip, String type) throws Exception {
		IpAreaAuthStatusRequestDtoBean ipareaauthstatusrequestdtoBean = new IpAreaAuthStatusRequestDtoBean();
		IpAreaAuthStatusRequestDtoCall ipareaauthstatusrequestdtoCall = new IpAreaAuthStatusRequestDtoCall();
		ipareaauthstatusrequestdtoBean.setIp(ip);
		ipareaauthstatusrequestdtoBean.setLoginId(loginId);
		ipareaauthstatusrequestdtoBean.setPassword(JUserCallService.defaultLoginPwd);
		ipareaauthstatusrequestdtoBean.setSuccess(true);
		ipareaauthstatusrequestdtoBean.setSource(type);
		ipareaauthstatusrequestdtoCall.setData(ipareaauthstatusrequestdtoBean);
		ipareaauthstatusrequestdtoCall.callService();
		return ipareaauthstatusrequestdtoCall;
	}

	/**
	 * 给userid用户设置安全问题
	 * 
	 * @param userid
	 * @throws Exception
	 */
	public static List<SecurityQuestionAnswer> setSecurityQuestion(Integer userid) throws Exception {
		Logger.comment("设置安全问题，userid:" + userid);
		List<SecurityQuestionAnswer> securityQuestionAnswerList = new ArrayList<>();
		SecurityQuestionAnswer securityQuestionAnswer1 = new SecurityQuestionAnswer();
		securityQuestionAnswer1.setQuestionId(1);
		securityQuestionAnswer1.setQuestionAnswer("测试1");
		securityQuestionAnswerList.add(securityQuestionAnswer1);

		SecurityQuestionAnswer securityQuestionAnswer2 = new SecurityQuestionAnswer();
		securityQuestionAnswer2.setQuestionId(2);
		securityQuestionAnswer2.setQuestionAnswer("测试2");
		securityQuestionAnswerList.add(securityQuestionAnswer2);

		SecurityQuestionAnswer securityQuestionAnswer3 = new SecurityQuestionAnswer();
		securityQuestionAnswer3.setQuestionId(3);
		securityQuestionAnswer3.setQuestionAnswer("测试3");
		securityQuestionAnswerList.add(securityQuestionAnswer3);

		SetSecurityQuestionBean setsecurityquestionBean = new SetSecurityQuestionBean();
		SetSecurityQuestionCall setsecurityquestionCall = new SetSecurityQuestionCall();

		setsecurityquestionBean.setUserId(userid);
		setsecurityquestionBean.setSecurityQuestionAnswerList(securityQuestionAnswerList);
		setsecurityquestionCall.setData(setsecurityquestionBean);
		setsecurityquestionCall.callService();
		return securityQuestionAnswerList;
	}

	/**
	 * 设置是否开启双重验证
	 * 
	 * @param userid
	 * @param enable
	 * @return
	 * @throws Exception
	 */
	public static SetDualSecurityRequestDtoCall setSecurity(Integer userid, Boolean enable) throws Exception {
		Logger.comment("设置双重认证，userid:" + userid + ",enable:" + enable);
		SetDualSecurityRequestDtoBean setdualsecurityrequestdtoBean = new SetDualSecurityRequestDtoBean();
		SetDualSecurityRequestDtoCall setdualsecurityrequestdtoCall = new SetDualSecurityRequestDtoCall();
		setdualsecurityrequestdtoBean.setUserId(userid);
		setdualsecurityrequestdtoBean.setEnable(enable);
		setdualsecurityrequestdtoCall.setData(setdualsecurityrequestdtoBean);
		setdualsecurityrequestdtoCall.callService();
		return setdualsecurityrequestdtoCall;
	}

	/**
	 * 查询双重验证
	 * 
	 * @param userid
	 * @return
	 * @throws Exception
	 */
	public static GetDualSecurityResultRequestDtoCall getSecurity(Integer userid) throws Exception {
		GetDualSecurityResultRequestDtoBean setdualsecurityrequestdtoBean = new GetDualSecurityResultRequestDtoBean();
		GetDualSecurityResultRequestDtoCall setdualsecurityrequestdtoCall = new GetDualSecurityResultRequestDtoCall();
		setdualsecurityrequestdtoBean.setUserId(userid);
		setdualsecurityrequestdtoCall.setData(setdualsecurityrequestdtoBean);
		setdualsecurityrequestdtoCall.callService();
		return setdualsecurityrequestdtoCall;
	}

	public static void main(String[] args) throws ClientProtocolException, IOException {
		// Logger.debug(AuthCallService.modifyLoginPassword("554416",
		// JUserCallService.defaultLoginPwd));
//		ArrayList<String> list = TestDataManager.getLines("./login");
//		for (String string : list) {
//			AuthCallServiceV2.authLogin(string, "1234D4321", "app", TestDataManager.getRandomIp());
//		}
		AuthCallServiceV2.createToken(500002617, DGUserCallService.DG_SellerWxApp.toString());
		
		// Logger.debug(AuthCallService.authLogin("丁丁", JUserCallService.defaultLoginPwd));

	}
}
